// ignore_for_file: file_names, depend_on_referenced_packages

import 'package:flutter/material.dart';
import 'package:verse_systems/res/colors.dart';
import 'package:verse_systems/widgets/drawer_appbar.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';

class WebViewPage extends StatefulWidget {
  final String? title;
  final String url;
  final bool isHtml;
  const WebViewPage(
      {super.key, this.title, required this.url, this.isHtml = false});

  static pushRouter(BuildContext context, String fileUrl,
      {String title = "详情", bool isHtml = false}) async {
    return Navigator.push(
        context,
        MaterialPageRoute(
            builder: (BuildContext context) => WebViewPage(
                  url: fileUrl,
                  title: title,
                  isHtml: isHtml,
                )));
  }

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  late final WebViewController _controller;

  late double progress = 0;

  @override
  void initState() {
    super.initState();
    late final PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

    final WebViewController controller =
        WebViewController.fromPlatformCreationParams(params);
    if (controller.platform is AndroidWebViewController) {
      AndroidWebViewController.enableDebugging(true);
      (controller.platform as AndroidWebViewController)
          .setMediaPlaybackRequiresUserGesture(false);
    }
    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            debugPrint("加载进度progress---$progress");
            setState(() {
              this.progress = progress / 100;
            });
          },
          onPageStarted: (String url) {},
          onPageFinished: (String url) {},
          onWebResourceError: (WebResourceError error) {
            debugPrint(
                "code:${error.errorCode}\n description: ${error.description} \n errorType: ${error.errorType} \nisForMainFrame: ${error.isForMainFrame}");
          },
          onNavigationRequest: (NavigationRequest request) {
            return NavigationDecision.navigate;
          },
        ),
      );

    _controller = controller;
    _loadUrl();
  }

  Future<void> _loadUrl() async {
    if (widget.isHtml) {
      return await _controller.loadHtmlString(widget.url);
    } else {
      return await _controller.loadRequest(
        Uri.parse(widget.url),
        method: LoadRequestMethod.get,
        headers: <String, String>{
          'Content-Type': 'text/html',
          'charset': 'utf-8'
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: DrawerAppbar(
          title: widget.title,
        ),
        body: Column(
          children: [
            progress < 1.0 ? _linearProgress : Container(),
            Expanded(child: WebViewWidget(controller: _controller))
          ],
        ));
  }

  Widget get _linearProgress {
    return Container(
        padding: const EdgeInsets.symmetric(vertical: 5),
        child: LinearProgressIndicator(
          value: progress,
          minHeight: 4,
          color: Colours.app_main_background_color,
        ));
  }
}
